package com.sky.netty;

import com.sky.handler.HandlerServerHello;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * 服务端启动类
 */
@Slf4j
public class AppServerHello {
    private int port;

    public AppServerHello(int port) {
        this.port = port;
    }

    @SneakyThrows
    public void run() {
        // Netty的Reactor线程池，初始化了一个NioEventLoop数组，用来处理I/O操作，如接受新的连接和读/写数据
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(group)
                    // 通过工厂方法设计模式实例化一个channel
                    .channel(NioServerSocketChannel.class)
                    // 设置监听端口
                    .localAddress(new InetSocketAddress(port))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 配置childHandler来通知一个关于消息处理的InfoServerHandler实例
                            ch.pipeline().addLast(new HandlerServerHello());
                        }
                    });

            // 绑定服务器，该实例将提供有关IO操作的结果或状态的信息
            ChannelFuture channelFuture = b.bind().sync();
            log.info("在{}上开启监听", channelFuture.channel().localAddress());

            // 阻塞操作，closeFutrue()开启了一个channel的监听器(这期间channel在进行各项工作),直到链路断开
            channelFuture.channel().closeFuture().sync();

        } finally {
            // 关闭EventLoopGroup并释放所有资源，包括所有创建的线程
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) {
        new AppServerHello(18080).run();
    }
}
